'''
Created on Aug 7, 2009

@author: mkiyer
'''

import sys
import math

cimport stdio

#cdef extern from "zlib.h":
#    ctypedef void* gzFile
#    gzFile gzopen(char *path, char *mode)
#    gzFile gzdopen(int fd, char *mode)
#    int gzprintf(gzFile file, char *format, ...)
#    int gzclose(gzFile file)

#cdef gzFile wigfp = NULL
#
#def wig_open():
#    pass
#
#def wig_close():
#    global wigfp
#    if wigfp != NULL:
#        gzclose(wigfp)
#    wigfp = NULL

cdef extern from "Python.h":
    stdio.FILE* PyFile_AsFile(object)
    
def write_wig_fixed_step(file fhd, char * chrom, cov_array, int span=-1):
    cdef unsigned int i
    cdef unsigned int prev_v
    cdef unsigned int v
    cdef unsigned int WRITING = 1
    cdef unsigned int SEARCHING = 0
    cdef unsigned int state = SEARCHING
    cdef stdio.FILE *wigfp
  
    #if wigfp == NULL
    #    wigfp = gzdopen(fhd.fileno(), "wb")
    wigfp = PyFile_AsFile(fhd)

    for i in xrange(len(cov_array)):
        v = cov_array[i]
        if v != 0:
            if state == SEARCHING:
                # write leading zero so that y axis scale includes zero
                if i > 0:
                    stdio.fprintf(wigfp, "fixedStep chrom=%s start=%d step=1\n", chrom, i)
                    stdio.fprintf(wigfp, "%d\n", 0)
                else:
                    stdio.fprintf(wigfp, "fixedStep chrom=%s start=%d step=1\n", chrom, i+1)
                state = WRITING
            stdio.fprintf(wigfp, "%d\n", v)
        else:
            # write trailing zero so that y axis scale includes zero
            if state == WRITING:
                stdio.fprintf(wigfp, "%d\n", 0)
            state = SEARCHING
    #gzprintf(wigfp, "%d\n", v)
    #gzclose(wigfp)
    return
    

#def write_wig_fixed_step2(fhd, chrom, cov_array, span=None):
#    # reduce entire chromosome to only the nonzero elements
#    a = numpy.flatnonzero(cov_array)
#    if len(a) == 0:
#        print 'write_wig_fixed_step: no nonzero elements in array'
#        return
#        
#    prev_i = a[0]
#    fhd.write("fixedStep chrom=%s start=%d step=1\n" % (chrom, prev_i+1))
#    fhd.write("%d\n" % cov_array[prev_i])    
#    for i in a[1:]:
#        if i != prev_i + 1:
#            fhd.write("fixedStep chrom=%s start=%d step=1\n" % (chrom, i+1))            
#        fhd.write("%d\n" % cov_array[i])
#        prev_i = i
#    return